import { h } from 'vue';
import { execScript, omit, ReceiveMessageEnum } from '@jecloud/utils';
import { Modal, Button, Drawer } from '@jecloud/ui';
import { useJE } from '@common/helper/je';
import { useWebSocketStore } from '@/stores/websocket-store';
import ScriptMessage from '@/data/model/websocket/script-message';
import NoticeMessage from '@/data/model/websocket/notice-message';
import noticeAudio from '@/assets/audio/notice.wav';
import '@/assets/styles/notice.less';
/**
 * 安装websocket
 */
export function setupWebSocket() {
  const websocketStore = useWebSocketStore();
  websocketStore.setupWebSocket({
    onMessage,
    onUnreadMessage,
  });
}
/**
 * WebSocket 消息监听
 * @param {*} message
 */
function onMessage(message) {
  const { type } = message;
  switch (type) {
    case ReceiveMessageEnum.SYS_MESSAGE: // 系统消息
      onSystemMessage(message);
      break;
    case ReceiveMessageEnum.SCRIPT_MESSAGE: // 脚本消息
      onScriptMessage(message);
      break;
    case ReceiveMessageEnum.NOTICE_MESSAGE: // 通知消息
      onNoticeMessage(message);
      break;
  }
}

/**
 * 未读消息处理
 * @param {Array} messages
 */
function onUnreadMessage(messages) {
  console.log(messages);
}
/**
 * 系统消息
 * @param {Object} message
 */
function onSystemMessage(message) {
  const websocketStore = useWebSocketStore();
  websocketStore.onMessage(message);
}
/**
 * 脚本消息
 * @param {Object} message
 */
function onScriptMessage(message) {
  const scriptMessage = new ScriptMessage(message);
  doCustomScript(scriptMessage);
}

/**
 * 通知消息
 * @param {Object} message
 */
function onNoticeMessage(message) {
  if (!message) return false;
  const notice = new NoticeMessage(message);
  // 播放声音
  if (notice.playAudio) {
    playNoticeAudio();
  }
  // if (useWebSocketStore().notices.length >= 0) {
  //   notice.buttons.push({
  //     script: '',
  //     text: `展开更多（${useWebSocketStore().notices.length + 1}）`,
  //     isShow: true,
  //   });
  // }
  // useWebSocketStore().notices.unshift(notice);

  // 通知框
  const { close } = Modal.notice({
    ...omit(notice, ['buttons', 'closable', 'content', 'createdTime', 'showClose', 'formatData']),
    class: 'message-notification',
    btn: () =>
      notice.buttons.map((button) => {
        return h(
          Button,
          {
            type: 'primary',
            size: 'small',
            style: { margin: '0 20px' },
            ...omit(button, ['text', 'script', 'params']),
            onClick() {
              // 执行按钮脚本
              const { script, params, isShow } = button;
              doCustomScript({ script, params: { ...params, closeNotice: close } });
              if (isShow) {
                showMoreNotice();
                close();
              }
            },
          },
          { default: () => button.text },
        );
      }),
  });
}

/**
 * 展示更多消息内容
 * @param {*}
 */
function showMoreNotice() {
  const { close } = Drawer.show({
    title: '',
    closeIcon: false,
    bodyStyle: {
      padding: '0 20px',
    },
    width: '260px',
    class: 'drawer-container',
    content() {
      return h('div', {}, [
        h('div', { style: { display: 'flex', justifyContent: 'space-between' } }, [
          h(
            Button,
            {
              type: 'primary',
              style: { width: '155px' },
              onClick: () => {
                useWebSocketStore().notices = [];
                close();
              },
            },
            '全部关闭',
          ),
          h(
            Button,
            {
              style: {
                width: '155px',
                border: '1px solid #d9d9d9',
                background: '#f5f5f5',
                color: '#3f3f3f',
              },
              onClick: () => {
                close();
              },
            },
            '全部收起',
          ),
        ]),
        [
          useWebSocketStore().notices.map((item, index) => {
            return h('div', { id: `item${index}` }, [
              h('div', { class: 'item-title' }, [
                h('div', {}, item.message),
                h('div', { style: { height: '48px' } }, [
                  h(
                    'span',
                    {
                      class: 'item-time',
                      style: { display: !item.showClose ? 'inline-block' : 'none' },
                      onMouseenter: () => {
                        useWebSocketStore().notices.map((_item) => {
                          _item.showClose = false;
                        });
                        item.showClose = true;
                      },
                      onMouseleave: () => {
                        useWebSocketStore().notices.map((_item) => {
                          _item.showClose = false;
                        });
                      },
                    },
                    item.createdTime,
                  ),
                  h('i', {
                    class: 'fal fa-times',
                    style: { display: item.showClose ? 'inline-block' : 'none' },
                    onClick: () => {
                      // 删除notices数据
                      useWebSocketStore().notices.splice(index, 1);
                      if (useWebSocketStore().notices.length == 0) {
                        close();
                      }
                    },
                  }),
                ]),
              ]),
              h('div', { class: 'item-content' }, item.content),
            ]);
          }),
        ],
      ]);
    },
  });
}

/**
 * 执行自定义脚本
 * @param {*} param0
 */
function doCustomScript({ script, params }) {
  if (script) {
    try {
      execScript(script, { EventOptions: params, JE: useJE() });
    } catch (error) {
      console.log(error);
    }
  }
}
/**
 * 播放声音
 * @returns
 */
function playNoticeAudio() {
  var audioId = '__JE_NOTICE_AUDIO_VOICE';
  var audio = document.getElementById(audioId);
  if (audio) {
    if (audio.currentTime > 0 && !audio.ended) {
      return;
    }
    document.body.removeChild(audio);
  }
  audio = document.createElement('audio');
  audio.setAttribute('id', audioId);
  audio.setAttribute('hidden', true);
  audio.setAttribute('src', noticeAudio);
  audio.setAttribute('autoplay', 'autoplay');
  document.body.appendChild(audio);
  return audio;
}

window.playNoticeAudio = playNoticeAudio;
